package com.wgl.order.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePayResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.wgl.model.enums.PaymentTypeEnum;
import com.wgl.model.enums.RefundStatusEnum;
import com.wgl.model.enums.ZfbEnum;
import com.wgl.model.order.OrderInfo;
import com.wgl.model.order.PaymentInfo;
import com.wgl.model.order.RefundInfo;
import com.wgl.order.service.OrderService;
import com.wgl.order.service.PaymentService;
import com.wgl.order.service.RefundService;
import com.wgl.order.service.ZfbService;
import io.micrometer.core.instrument.binder.BaseUnits;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wgl
 * @version 1.0.0
 * @ClassName ZfbServiceImpl.java
 * @Description TODO
 * @createTime 2022年02月14日 22:30:00
 */
@Service
public class ZfbServiceImpl implements ZfbService {
    //支付成功后要跳转的页面
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    @Resource
    private OrderService orderService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private RefundService refundService;
    @Resource
    private RedisTemplate redisTemplate;
    Rock



    @Override
    public Map createNative(Long orderId) {
        //从redis获取数据
        Map payMap = (Map)redisTemplate.opsForValue().get(orderId.toString());
        if(payMap != null) {
            return payMap;
        }
//        得到订单表
//        bo.setSubject("充值");
        OrderInfo orderInfo = orderService.getById(orderId);
//        向支付记录表添加记录
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.ALIPAY.getStatus());
        //发送请求
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        request.setBizModel(model);
//        model.setOutTradeNo(System.currentTimeMills());
        model.setTotalAmount(String.valueOf(orderInfo.getAmount()));
        model.setSubject(orderInfo.getHosname()+"-"+orderInfo.getDepname()+"挂号费");
        model.setOutTradeNo(orderInfo.getOutTradeNo());
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //这里的response.body，就是一个可以直接加载的html片段，
        // 这里为了简单我直接返回这个片段
//        redisTemplate.opsForValue().set(orderNo, bo.getUser_id(),10, TimeUnit.MINUTES);
//        System.out.println(orderNo);
        Map map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("totalFee", orderInfo.getAmount());
        map.put("resultCode", response.getCode());
        map.put("codeUrl",response.getQrCode());
//        map.put("codeUrl1",response);
        if(response.getCode() != null) {
            redisTemplate.opsForValue().set(orderId.toString(),map,120, TimeUnit.MINUTES);
        }
        return map;
    }

    @Override
    public String queryPayStatus(Long orderId) {
        //得到订单
        OrderInfo orderInfo = orderService.getById(orderId);
        if (orderId == null){
            return null;
        }
//        Factory.Base.Qrcode().create()
        //查询支付宝 是否支持成功
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
//bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            String tradeStatus = response.getTradeStatus();
//            System.out.println();
//            System.out.println(map);
            if (ZfbEnum.TRADE_SUCCESS.getStatus().equals(tradeStatus)){
                //支付完成
                Map<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(response), Map.class);
                map.remove("body");
                paymentService.paySuccess(orderInfo.getOutTradeNo(),map);
            }
//            System.out.println(ZfbEnum.getStatusName(tradeStatus));
            return ZfbEnum.getStatusName(tradeStatus);
//            return "支付中";
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public Boolean refund(Long orderId) {
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.ALIPAY.getStatus());
        //加入退款记录表
        RefundInfo refundInfo = refundService.saveRefundInfo(paymentInfo);
        if (refundInfo.getRefundStatus().intValue()  == RefundStatusEnum.REFUND.getStatus().intValue()){
            //已退款
            return true;
        }
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", paymentInfo.getTradeNo());
        bizContent.put("refund_amount", paymentInfo.getTotalAmount());
        bizContent.put("out_request_no", paymentInfo.getOutTradeNo());


        request.setBizContent(bizContent.toString());
        try {
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if ("10000".equals(response.getCode())){
                //退款成功
                //更新退款表的数据
                //修改时间
                refundInfo.setCallbackTime(new Date());
                //交易号
                refundInfo.setTradeNo(response.getTradeNo());
                //退款状态
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                //返回的响应数据
                response.setBody(null);
                refundInfo.setCallbackContent(JSONObject.toJSONString(response));
                refundService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Object dl() {

        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
        request.setCode("4b203fe6c11548bcabd8da5bb087a83b");
        request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        try {
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            return response;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
